<template>
  <div class="payment-links-table">
    <!-- 批量操作区域 -->
    <div v-if="selectedLinks.length > 0" class="batch-operations">
      <div class="selected-count">
        已选择 <span class="count">{{ selectedLinks.length }}</span> 个链接
      </div>
      <div class="operation-buttons">
        <button class="btn btn-danger" @click="handleBatchDelete">
          <i class="fas fa-trash-alt"></i> 批量删除
        </button>
        <button class="btn btn-info" @click="handleBatchExport">
          <i class="fas fa-file-export"></i> 导出数据
        </button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="links-table">
      <table>
        <thead>
          <tr>
            <th class="checkbox-column">
              <input
                type="checkbox"
                :checked="selectAll"
                :indeterminate="indeterminate"
                @change="toggleSelectAll"
              />
            </th>
            <th>商品信息</th>
            <th class="price-column">
              <div class="sortable-header" @click="toggleSort('price')">
                价格
                <i
                  class="fas"
                  :class="{
                    'fa-sort': sortColumn !== 'price',
                    'fa-sort-up': sortColumn === 'price' && sortDirection === 'asc',
                    'fa-sort-down': sortColumn === 'price' && sortDirection === 'desc'
                  }"
                ></i>
              </div>
            </th>
            <th class="date-column">
              <div class="sortable-header" @click="toggleSort('createdAt')">
                创建时间
                <i
                  class="fas"
                  :class="{
                    'fa-sort': sortColumn !== 'createdAt',
                    'fa-sort-up': sortColumn === 'createdAt' && sortDirection === 'asc',
                    'fa-sort-down': sortColumn === 'createdAt' && sortDirection === 'desc'
                  }"
                ></i>
              </div>
            </th>
            <th>设置名称</th>
            <th class="remark-column">客户备注</th>
            <th class="action-column">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading" class="loading-row">
            <td colspan="7">
              <div class="loading-indicator">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载中...</span>
              </div>
            </td>
          </tr>
          <tr v-else-if="paginatedLinks.length === 0" class="empty-row">
            <td colspan="7">
              <div class="empty-message">
                <i class="fas fa-link"></i>
                <p>暂无符合条件的支付链接</p>
              </div>
            </td>
          </tr>
          <tr
            v-for="link in paginatedLinks"
            :key="link.id"
            :class="{ 'selected-row': selectedIds.includes(link.id) }"
          >
            <td class="checkbox-column">
              <input
                type="checkbox"
                :checked="selectedIds.includes(link.id)"
                @change="toggleSelect(link.id)"
              />
            </td>
            <td class="product-info">
              <div class="product-image" @click="previewImage(link.productImage)">
                <img :src="link.productImage" :alt="link.productName" />
              </div>
              <div class="product-details">
                <div class="product-name">{{ link.productName }}</div>
                <div class="restaurant-name">{{ link.restaurantName }}</div>
              </div>
            </td>
            <td class="price-column">
              <div class="discount-price">¥{{ formatNumber(link.discountPrice) }}</div>
              <div class="original-price">¥{{ formatNumber(link.originalPrice) }}</div>
              <div class="discount-badge">
                {{ calculateDiscount(link.originalPrice, link.discountPrice) }}折
              </div>
            </td>
            <td class="date-column">
              <div class="created-date">{{ formatDate(link.createdAt) }}</div>
            </td>
            <td class="name-column">
              <div class="custom-name">{{ link.name }}</div>
            </td>
            <td class="remark-column">
              <div class="remark-editor">
                <textarea
                  class="remark-input"
                  :value="link.remark || ''"
                  :placeholder="editingRemarkId === link.id ? '' : '点击添加备注...'"
                  @focus="startEditRemark(link.id)"
                  @blur="saveRemark(link.id, $event.target ? ($event.target as HTMLTextAreaElement).value : '')"
                  @input="updateRemarkValue($event)"
                ></textarea>
                <div v-if="editingRemarkId === link.id" class="remark-hint">
                  编辑中，失去焦点自动保存
                </div>
              </div>
            </td>
            <td class="action-column">
              <div class="action-buttons">
                <button class="action-btn copy-btn" @click="copyLink(link)">
                  <i class="fas fa-copy"></i>
                </button>
                <button class="action-btn share-btn" @click="shareLink(link)">
                  <i class="fas fa-share-alt"></i>
                </button>
                <button class="action-btn view-btn" @click="viewLinkDetails(link)">
                  <i class="fas fa-eye"></i>
                </button>
                <button class="action-btn delete-btn" @click="deleteLink(link)">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <div class="pagination-info">
        显示 {{ paginationInfo }}
      </div>
      <div class="pagination">
        <button
          class="pagination-btn"
          :disabled="currentPage === 1"
          @click="changePage(1)"
        >
          <i class="fas fa-angle-double-left"></i>
        </button>
        <button
          class="pagination-btn"
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
        >
          <i class="fas fa-angle-left"></i>
        </button>
        
        <template v-for="page in displayedPages" :key="page">
          <span v-if="page === '...'" class="ellipsis">...</span>
          <button
            v-else
            class="pagination-btn"
            :class="{ active: currentPage === page }"
            @click="changePage(page as number)"
          >
            {{ page }}
          </button>
        </template>
        
        <button
          class="pagination-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
        >
          <i class="fas fa-angle-right"></i>
        </button>
        <button
          class="pagination-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(totalPages)"
        >
          <i class="fas fa-angle-double-right"></i>
        </button>
      </div>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="previewImageUrl" class="image-preview-modal" @click="closePreview">
      <div class="preview-container">
        <img :src="previewImageUrl" alt="商品预览" />
        <button class="close-preview" @click.stop="closePreview">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'

interface PaymentLink {
  id: string
  name: string
  productId: string
  productName: string
  restaurantName: string
  productImage: string
  originalPrice: number
  discountPrice: number
  commission: number
  createdAt: string
  status: 'active' | 'inactive'
  isActive: boolean
  url: string
  remark?: string
}

interface Props {
  links: PaymentLink[]
  loading: boolean
  itemsPerPage?: number
}

const props = withDefaults(defineProps<Props>(), {
  itemsPerPage: 10
})

const emit = defineEmits<{
  (e: 'sort', column: string, direction: 'asc' | 'desc'): void
  (e: 'copy', link: PaymentLink): void
  (e: 'share', link: PaymentLink): void
  (e: 'view', link: PaymentLink): void
  (e: 'delete', link: PaymentLink): void
  (e: 'batch-delete', ids: string[]): void
  (e: 'batch-export', ids: string[]): void
  (e: 'toggle-status', link: PaymentLink, status: boolean): void
  (e: 'update-remark', linkId: string, remark: string): void
}>()

// 排序状态
const sortColumn = ref<string>('')
const sortDirection = ref<'asc' | 'desc'>('desc')

// 分页状态
const currentPage = ref(1)

// 图片预览状态
const previewImageUrl = ref<string | null>(null)

// 选择状态
const selectedIds = ref<string[]>([])

// 备注编辑状态
const editingRemarkId = ref<string | null>(null)
const remarkValue = ref('')

// 计算排序后的数据
const sortedLinks = computed(() => {
  if (!sortColumn.value) return [...props.links]

  return [...props.links].sort((a, b) => {
    let aValue, bValue

    switch (sortColumn.value) {
      case 'price':
        aValue = a.discountPrice
        bValue = b.discountPrice
        break
      case 'createdAt':
        aValue = new Date(a.createdAt).getTime()
        bValue = new Date(b.createdAt).getTime()
        break
      default:
        return 0
    }

    if (sortDirection.value === 'asc') {
      return aValue > bValue ? 1 : -1
    } else {
      return aValue < bValue ? 1 : -1
    }
  })
})

// 当前页数据
const paginatedLinks = computed(() => {
  const startIndex = (currentPage.value - 1) * props.itemsPerPage
  const endIndex = startIndex + props.itemsPerPage
  return sortedLinks.value.slice(startIndex, endIndex)
})

// 总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(props.links.length / props.itemsPerPage))
})

// 显示的页码
const displayedPages = computed<(number | string)[]>(() => {
  const result: (number | string)[] = []
  const maxVisiblePages = 5
  
  if (totalPages.value <= maxVisiblePages) {
    // 总页数小于等于最大可见页数，显示所有页码
    for (let i = 1; i <= totalPages.value; i++) {
      result.push(i)
    }
  } else {
    // 总页数大于最大可见页数，显示部分页码
    const halfVisible = Math.floor(maxVisiblePages / 2)
    
    // 当前页在前半部分
    if (currentPage.value <= halfVisible + 1) {
      for (let i = 1; i <= maxVisiblePages - 1; i++) {
        result.push(i)
      }
      result.push('...')
      result.push(totalPages.value)
    } 
    // 当前页在后半部分
    else if (currentPage.value >= totalPages.value - halfVisible) {
      result.push(1)
      result.push('...')
      for (let i = totalPages.value - (maxVisiblePages - 2); i <= totalPages.value; i++) {
        result.push(i)
      }
    } 
    // 当前页在中间部分
    else {
      result.push(1)
      result.push('...')
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        result.push(i)
      }
      result.push('...')
      result.push(totalPages.value)
    }
  }
  
  return result
})

// 分页信息
const paginationInfo = computed(() => {
  const startItem = props.links.length === 0 ? 0 : (currentPage.value - 1) * props.itemsPerPage + 1
  const endItem = Math.min(currentPage.value * props.itemsPerPage, props.links.length)
  return `${startItem}-${endItem} 项，共 ${props.links.length} 项`
})

// 选中的链接数据
const selectedLinks = computed(() => {
  return props.links.filter(link => selectedIds.value.includes(link.id))
})

// 全选状态
const selectAll = computed(() => {
  return props.links.length > 0 && selectedIds.value.length === props.links.length
})

// 部分选择状态
const indeterminate = computed(() => {
  return selectedIds.value.length > 0 && selectedIds.value.length < props.links.length
})

// 监听数据变化，重置分页
watch(() => props.links.length, () => {
  if (currentPage.value > totalPages.value) {
    currentPage.value = Math.max(1, totalPages.value)
  }
})

// 切换排序
const toggleSort = (column: string) => {
  if (sortColumn.value === column) {
    // 切换排序方向
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    // 更换排序列
    sortColumn.value = column
    sortDirection.value = 'desc'
  }
  
  emit('sort', column, sortDirection.value)
}

// 切换页码
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 格式化数字
const formatNumber = (num: number) => {
  return num.toFixed(2)
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 计算折扣率
const calculateDiscount = (originalPrice: number, discountPrice: number) => {
  return ((discountPrice / originalPrice) * 10).toFixed(1)
}

// 预览图片
const previewImage = (imageUrl: string) => {
  previewImageUrl.value = imageUrl
}

// 关闭预览
const closePreview = () => {
  previewImageUrl.value = null
}

// 复制链接
const copyLink = (link: PaymentLink) => {
  emit('copy', link)
}

// 分享链接
const shareLink = (link: PaymentLink) => {
  emit('share', link)
}

// 查看链接详情
const viewLinkDetails = (link: PaymentLink) => {
  emit('view', link)
}

// 删除链接
const deleteLink = (link: PaymentLink) => {
  emit('delete', link)
}

// 切换链接状态
const toggleLinkStatus = (link: PaymentLink) => {
  emit('toggle-status', link, !link.isActive)
}

// 切换选择单个链接
const toggleSelect = (id: string) => {
  if (selectedIds.value.includes(id)) {
    selectedIds.value = selectedIds.value.filter(item => item !== id)
  } else {
    selectedIds.value.push(id)
  }
}

// 切换全选/取消全选
const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedIds.value = []
  } else {
    selectedIds.value = props.links.map(link => link.id)
  }
}

// 批量删除
const handleBatchDelete = () => {
  emit('batch-delete', selectedIds.value)
}

// 批量导出
const handleBatchExport = () => {
  emit('batch-export', selectedIds.value)
}

// 开始编辑备注
const startEditRemark = (linkId: string) => {
  editingRemarkId.value = linkId
  const link = props.links.find(link => link.id === linkId)
  remarkValue.value = link?.remark || ''
}

// 更新备注内容
const updateRemarkValue = (event: Event) => {
  const target = event.target as HTMLTextAreaElement
  if (target) {
    remarkValue.value = target.value
  }
}

// 保存备注
const saveRemark = (linkId: string, value: string) => {
  const trimmedValue = value.trim()
  editingRemarkId.value = null
  
  // 查找链接对象
  const link = props.links.find(link => link.id === linkId)
  if (!link) return
  
  // 如果备注没有改变，不发送更新事件
  if (link.remark === trimmedValue) return
  
  // 发送更新备注事件
  emit('update-remark', linkId, trimmedValue)
}
</script>

<style scoped lang="scss">
.payment-links-table {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 24px;
  
  // 批量操作区域
  .batch-operations {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background-color: #f8fafc;
    border-bottom: 1px solid #eaeef2;
    
    .selected-count {
      font-size: 14px;
      color: #4b5563;
      
      .count {
        font-weight: 600;
        color: #FF4757;
        margin: 0 2px;
      }
    }
    
    .operation-buttons {
      display: flex;
      gap: 12px;
      
      .btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 8px 16px;
        border-radius: 6px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        border: none;
        transition: all 0.2s ease;
        
        i {
          margin-right: 6px;
          font-size: 14px;
        }
        
        &.btn-danger {
          background-color: #FF4757;
          color: #fff;
          
          &:hover {
            background-color: darken(#FF4757, 8%);
            transform: translateY(-1px);
            box-shadow: 0 3px 8px rgba(255, 71, 87, 0.2);
          }
        }
        
        &.btn-info {
          background-color: #2F3542;
          color: #fff;
          
          &:hover {
            background-color: darken(#2F3542, 8%);
            transform: translateY(-1px);
            box-shadow: 0 3px 8px rgba(47, 53, 66, 0.2);
          }
        }
      }
    }
  }
  
  // 表格样式
  .links-table {
    width: 100%;
    overflow-x: auto;
    
    table {
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
      table-layout: fixed;
      
      th, td {
        padding: 16px;
        text-align: left;
        vertical-align: middle;
        border-bottom: 1px solid #eaeef2;
      }
      
      th {
        font-weight: 600;
        font-size: 13px;
        color: #4b5563;
        background-color: #f8fafc;
        position: sticky;
        top: 0;
        z-index: 10;
        
        .sortable-header {
          display: flex;
          align-items: center;
          cursor: pointer;
          
          i {
            margin-left: 5px;
            color: #9ca3af;
            
            &.fa-sort-up,
            &.fa-sort-down {
              color: #FF4757;
            }
          }
          
          &:hover {
            color: #FF4757;
          }
        }
      }
      
      thead tr {
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
      }
      
      tbody tr {
        transition: background-color 0.15s ease;
        
        &:hover {
          background-color: #f9fafb;
        }
        
        &.selected-row {
          background-color: rgba(255, 71, 87, 0.04);
          
          &:hover {
            background-color: rgba(255, 71, 87, 0.08);
          }
        }
      }
      
      .loading-row,
      .empty-row {
        td {
          padding: 48px 0;
          text-align: center;
        }
      }
      
      .loading-indicator,
      .empty-message {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #9ca3af;
        
        i {
          font-size: 36px;
          margin-bottom: 16px;
          color: #d1d5db;
        }
        
        p {
          font-size: 14px;
          margin: 0;
        }
      }
      
      // 商品信息列
      .product-info {
        display: flex;
        align-items: center;
        width: 25%;
        
        .product-image {
          width: 52px;
          height: 52px;
          border-radius: 6px;
          overflow: hidden;
          margin-right: 14px;
          cursor: pointer;
          border: 1px solid #eaeef2;
          flex-shrink: 0;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
          }
          
          &:hover img {
            transform: scale(1.08);
          }
        }
        
        .product-details {
          flex: 1;
          min-width: 0;
          
          .product-name {
            font-size: 14px;
            font-weight: 500;
            color: #1f2937;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .restaurant-name {
            font-size: 12px;
            color: #6b7280;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
      
      // 价格列
      .price-column {
        width: 15%;
        
        .discount-price {
          font-size: 16px;
          font-weight: 600;
          color: #FF4757;
          margin-bottom: 3px;
        }
        
        .original-price {
          font-size: 12px;
          color: #9ca3af;
          text-decoration: line-through;
          margin-bottom: 5px;
        }
        
        .discount-badge {
          display: inline-block;
          font-size: 11px;
          padding: 2px 6px;
          border-radius: 12px;
          background-color: #fff0f0;
          color: #FF4757;
          font-weight: 500;
        }
      }
      
      // 日期列
      .date-column {
        width: 12%;
        
        .created-date {
          font-size: 13px;
          color: #4b5563;
          font-weight: 500;
        }
      }
      
      // 名称列
      .name-column {
        width: 12%;
        
        .custom-name {
          font-size: 14px;
          color: #1f2937;
          max-width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-weight: 500;
        }
      }
      
      // 备注列
      .remark-column {
        width: 18%;
        
        .remark-editor {
          position: relative;
          
          .remark-input {
            width: 100%;
            min-height: 64px;
            padding: 10px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            resize: vertical;
            font-size: 13px;
            font-family: inherit;
            transition: all 0.2s ease;
            background-color: #f9fafb;
            
            &:focus {
              outline: none;
              border-color: #FF4757;
              background-color: white;
              box-shadow: 0 0 0 3px rgba(255, 71, 87, 0.1);
            }
            
            &::placeholder {
              color: #9ca3af;
              font-style: italic;
            }
          }
          
          .remark-hint {
            position: absolute;
            bottom: -18px;
            left: 0;
            font-size: 11px;
            color: #6b7280;
            font-style: italic;
            background-color: rgba(255, 255, 255, 0.8);
            padding: 2px 4px;
            border-radius: 2px;
          }
        }
      }
      
      // 操作列
      .action-column {
        width: 13%;
        
        .action-buttons {
          display: flex;
          justify-content: space-evenly;
          gap: 4px;
          
          .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 6px;
            border: none;
            background-color: #f3f4f6;
            color: #4b5563;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }
            
            &.copy-btn:hover {
              background-color: #0ea5e9;
              color: #fff;
            }
            
            &.share-btn:hover {
              background-color: #8b5cf6;
              color: #fff;
            }
            
            &.view-btn:hover {
              background-color: #2F3542;
              color: #fff;
            }
            
            &.delete-btn:hover {
              background-color: #FF4757;
              color: #fff;
            }
          }
        }
      }
      
      // 其他小列
      .checkbox-column {
        width: 5%;
        text-align: center;
        
        input[type="checkbox"] {
          width: 18px;
          height: 18px;
          cursor: pointer;
          accent-color: #FF4757;
        }
      }
    }
  }
  
  // 分页控件
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-top: 1px solid #eaeef2;
    background-color: #f8fafc;
    
    .pagination-info {
      font-size: 13px;
      color: #6b7280;
    }
    
    .pagination {
      display: flex;
      align-items: center;
      gap: 6px;
      
      .pagination-btn {
        min-width: 34px;
        height: 34px;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
        background-color: #fff;
        color: #4b5563;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 13px;
        
        &.active {
          background-color: #FF4757;
          color: #fff;
          border-color: #FF4757;
          font-weight: 500;
        }
        
        &:disabled {
          opacity: 0.4;
          cursor: not-allowed;
        }
        
        &:not(:disabled):hover {
          background-color: #f3f4f6;
          border-color: #d1d5db;
          transform: translateY(-1px);
        }
      }
      
      .ellipsis {
        min-width: 34px;
        text-align: center;
        color: #6b7280;
      }
    }
  }
  
  // 图片预览模态框
  .image-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.75);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    backdrop-filter: blur(2px);
    
    .preview-container {
      position: relative;
      max-width: 80%;
      max-height: 80%;
      
      img {
        max-width: 100%;
        max-height: 80vh;
        border-radius: 8px;
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
      }
      
      .close-preview {
        position: absolute;
        top: -18px;
        right: -18px;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: #fff;
        color: #1f2937;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        cursor: pointer;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
        transition: all 0.2s;
        
        &:hover {
          background-color: #f3f4f6;
          transform: scale(1.05);
        }
      }
    }
  }
}

// 响应式样式
@media (max-width: 992px) {
  .payment-links-table {
    .links-table {
      table {
        .name-column {
          display: none;
        }
      }
    }
    
    .batch-operations {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
    }
  }
}

@media (max-width: 768px) {
  .payment-links-table {
    .links-table {
      table {
        .date-column {
          display: none;
        }
      }
    }
    
    .pagination-container {
      flex-direction: column;
      gap: 10px;
      
      .pagination-info {
        order: 2;
      }
      
      .pagination {
        order: 1;
      }
    }
  }
}

@media (max-width: 576px) {
  .payment-links-table {
    .links-table {
      table {
        .remark-column {
          display: none;
        }
      }
    }
  }
}
</style> 